<template>
  <el-dialog v-model="dialogVisible" :title="roleID ? '修改角色' : '新增角色'" width="600" @close="close">
    <template #default>
      <el-form model="rolefrom">
        <!-- 添加搜索框-->
        <!-- 角色名称 -->
        <el-form-item label="角色名称">
          <el-input v-model="rolefrom.roleName" placeholder="请输入角色名称">
          </el-input>
        </el-form-item>
        <!-- 权限字符 -->
        <el-form-item label="权限字符">
          <el-input v-model="rolefrom.rolePerm" placeholder="请输入权限字符">
          </el-input>
        </el-form-item>
        <!-- 状态 -->
        <el-form-item label="状态">
          <el-radio-group v-model="rolefrom.enabled">
            <el-radio v-for="item in dicts.system_global_status" :key="item.id"
              :label="rolefrom.enabled == item.v ? rolefrom.enabled : item.v">{{
                item.k
              }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 多选按钮 -->
        <el-form-item label="菜单权限">
          <div class="item-menu">
            <el-checkbox v-model="permission.openall" @change="toggleTreeapse">展开/折叠</el-checkbox>
            <el-checkbox v-model="permission.selectall" @change="toggleTreenChenckbox">全选/全不选</el-checkbox>
            <el-checkbox v-model="permission.linkage">父子(联动/不联动)</el-checkbox>
            <el-tree style="max-width: 600px" ref="menuTreenRef" :data="permission.treeList"
              :default-expand-all="permission.openall" :check-strictly="!permission.linkage"
              :props="permission.treenprops" show-checkbox node-key="id" class="tree">
            </el-tree>
          </div>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注">
          <el-input v-model="rolefrom.descript" type="textarea" placeholder="请输入备注内容" :maxlength="200" show-word-limit>

          </el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button @click="onSubmint" type="primary">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { menuTree, IRoleMenuItem, roleAdd, roleget, updateRole } from '@api/role'
import { ElMessage, ElTree } from 'element-plus'
import { ref, reactive, ComponentInternalInstance, getCurrentInstance, onBeforeMount } from 'vue'
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    // 为默认值
    default: false
  },
  roleID: {
    type: String,
    default: ''
  }
})
// 菜单节点的dom
const menuTreenRef = ref<InstanceType<typeof ElTree>>()
// 用于判断弹框类型的id
const roleID = ref(props.roleID)
//弹窗的状态
const dialogVisible = ref(props.dialogVisible)
//关闭弹窗的回调函数
const emit = defineEmits();
const close = () => {
  emit('dialogVisible', false)
}
// 表单数据
const rolefrom: {
  roleName: string
  rolePerm: string
  enabled: number
  descript: string | null
  id: string
} = reactive({
  roleName: '', //角色名称
  rolePerm: '',//角色权限编码
  enabled: 1,//是否启用（0：禁用；1：启用）
  descript: '',//描述
  id: ""
})
// 数据类型
interface Ipermission {
  treeList: IRoleMenuItem[],
  treenprops: {
    label: string
  },
  linkage: boolean,
  openall: boolean,
  selectall: boolean
}

// 菜单树
const permission: Ipermission = reactive({
  treeList: [],
  treenprops: {
    label: "name"
  },
  linkage: true,
  openall: false,
  selectall: false
})
// 展开/折叠
const toggleTreeapse = (e: boolean) => {
  // 获取到所有的dom节点
  let nodeMap = menuTreenRef.value!.store.nodesMap;  // nodeMap 对象的所有可枚举属性（键），并将 nodeMap 中每个属性对应的值对象的 expanded 属性设置为变量 e 的值。
  Object.keys(nodeMap).forEach(key => {
    nodeMap[key].expanded = e
  })
}

// 全选/全不选
const toggleTreenChenckbox = (e: boolean) => {
  // 获取到所有的dom节点
  let nodeMap = menuTreenRef.value!.store.nodesMap;
  // nodeMap 对象的所有可枚举属性（键），并将 nodeMap 中每个属性对应的值对象的 expanded 属性设置为变量 e 的值。
  Object.keys(nodeMap).forEach(key => {
    nodeMap[key].checked = e
  })
}
// 点击确定按钮
const onSubmint = async () => {
  if (rolefrom.roleName == '') return ElMessage.error('角色名称不能为空')
  if (rolefrom.rolePerm == '') return ElMessage.error('权限编码不能为空')
  if (rolefrom.enabled == '') return ElMessage.error('请选择状态')
  if (menuTreenRef.value!.getCheckedKeys() as string[] == '') return ElMessage.error('请选择部门')
  if (roleID.value != '') {
    await updateRoles()
  } else {
    await addRole()
  }
  // 点击确定按钮时关闭弹窗
  close()
  // 将数据传递过去
  emit('roleChange')
}
// menuTreenRef 引用的值中获取的已选中键作为 permissionIds 数组传递给 roleAdd 函数，最后将函数的返回结果打印到控制台。
// 新增
const addRole = async () => {
  return await roleAdd({
    ...rolefrom,
    permissionIds: menuTreenRef.value!.getCheckedKeys() as string[]
  })
}
// 编辑
const updateRoles = async () => {
  return await updateRole({
    ...rolefrom,
    permissionIds: menuTreenRef.value!.getCheckedKeys() as string[]
  })
}

onBeforeMount(async () => {
  const { proxy } = getCurrentInstance() as ComponentInternalInstance
  if (proxy) {
    (proxy as any).getDicts(['system_global_status'])
  }
  // 获取权限菜单
  let res = await menuTree()
  permission.treeList = res.data

  // 请求编辑接口
  if (roleID.value != '') {
    // 请求编辑接口
    let res = await roleget(roleID.value)
    let data = res.data
    menuTreenRef.value?.setCheckedKeys(data.permissions)
    let { descript, roleName, enabled, rolePerm, id } = data.role;
    rolefrom.descript = descript
    rolefrom.roleName = roleName
    rolefrom.enabled = enabled
    rolefrom.rolePerm = rolePerm
    rolefrom.id = id
  }
})
</script>

<style scoped>
.tree {
  border: 1px solid #dcdfe6;
  margin-top: 0.5rem;
  background-color: #FFF;
  border-radius: 4px;
}
</style>
